<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use Qiniu\Auth;
use OSS\OssClient;
use OSS\Core\OssException;
class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '信息已过期，请重新登录~';
    protected $frost = '您的账号已被冻结';
    protected $del = '您的账号已被删除';
    // 构造函数
    public function _initialize(){
        // 如果配置项为空 则直接返回

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){ // 冻结
                return 110;
            }
            if($user['user_status'] == 3){ // 删除
                return 1103;
            }
            $token = $user['user_token2'];
            $appId = "A2020308310121";
            $appkey = "9PA807B0-BE12-S521-6998-6D57B0CCE8ON";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                return 111;
            }
        }
    }
    /**
     * 获取七牛token
     * @return string
     */
    public function getQiniuToken(){
        require_once ('../extend/qiniu/autoload.php');
        header("Access-Control-Allow-Origin:*");
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
//        $auth = new Qiniu();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return json(array('data'=>$token));
    }
    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $SpCode = '230149';
        $LoginName = 'js_px';
        $Password = 'panson58398860';
        $MessageContent = iconv("UTF-8", "gbk//TRANSLIT", "您的验证码为{$num}，请在10分钟内使用！");
        $body = "SpCode=$SpCode&LoginName=$LoginName&Password=$Password&MessageContent=$MessageContent&UserNumber=$phone&SerialNumber=&ScheduleTime=&f=1";
        $header = array(
            'Accept:application/x-www-form-urlencoded',
            'Content-Type: application/x-www-form-urlencoded; charset=gbk'
        );
        $url = 'http://gd.ums86.com:8899/sms/Api/Send.do';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = mb_convert_encoding($result,'UTF-8','GBk');
        $res = explode('&',$result);
        return $res;
    }
    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)
    public function uploadFile()
    {
        $tmp = $_FILES['image']['tmp_name'];
        $name = $_FILES['image']['name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
//            if(!in_array($exe,$imgarray)){
//                return json(['status'=>0,'msg'=>'图片格式不支持']);
//            }
//            $newName = $rand . '.' .$exe;
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/image/{$newName}")){
                $imgUrl = "{$url}/image/{$newName}";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/image/{$newName}","{$dir}/image/{$newName}");
                }
                return json(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }

    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
//    function getRandChar($length)
//    {
//        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
//            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
//            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
//            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
//            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
//            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
//        $char_txt = '';
//        for ($i = 0; $i < $length; $i++) {
//            $char_txt .= $chars[array_rand($chars)];
//        }
//        return $char_txt;
//    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    //------------------------mww-------------------------------------------------------

    /**
     * 获取我的默认地址或者根据地址id获取地址信息
     * @param $user_id
     * @param $address_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function myAddressInfo($user_id,$address_id,$address_uson_id='')
    {
        $where = [
            'address_user_id' => $user_id,
            'address_del' => 1
        ];
        if($address_uson_id){
            $where['address_uson_id'] = $address_uson_id;
        }
        if($address_id){
            $where = ['address_id' => $address_id];
        }
        $field = 'u.*';
        $field .= ',a.district sheng,aa.district shi,aaa.district qu';
        $address = Db::table('up_my_address')->alias('u')
            ->join('up_area a','u.address_sheng=a.district_id','LEFT')
            ->join('up_area aa','u.address_shi=aa.district_id','LEFT')
            ->join('up_area aaa','u.address_qu=aaa.district_id','LEFT')
            ->where($where)
            ->order('address_default DESC')
            ->field($field)
            ->find();
        return $address;
    }
    /**
     * 立即购买处单件的详情
     *
     */
    public function lijigoumai($good_id,$attr_id,$num)
    {
        $good = Db::table('up_self_goods')
            ->where('good_id',$good_id)
            ->find();
        $attr = Db::table('up_self_goods_attr')
            ->where('attr_id',$attr_id)
            ->field('stock,sign_str,price')
            ->find();
        if($good['good_status'] == 2){
            $res = ['status'=>0,'msg'=>'商品已下架'];
            return $res;
        }
        $stock = $attr['stock'];
        if($stock < $num){
            $res = ['status'=>0,'msg'=>'库存不足'];
            return $res;
        }
        $postmanprice = $this->getpostmanalltype($good_id,1,$num);
        $good['sign_str'] = $attr['sign_str']; //规格
        $good['price'] = $attr['price']; //单价
        $good['allprice'] = $attr['price'] * $num + $postmanprice; //总价
        $good['postman'] = $postmanprice;
        $res = ['status'=>200,'msg'=>$good];
        return $res;
    }
    /**
     * 立即购买处单件的详情（增补）
     *
     */
    public function lijigoumaips($good_id,$attr_id,$num,$sondata)
    {
        $good = Db::table('up_goods')
            ->where('good_id',$good_id)
            ->find();

        if($good['good_status'] == 2){
            $res = ['status'=>0,'msg'=>'商品已下架'];
            return $res;
        }
        //购物车的话year还是要存一下的
        $good['good_price'] = getGoodsRealPrice($good['good_coding'],$sondata['uson_year'],$sondata);
        $postmanprice = $this->getpostmanalltype($good_id,1,$num);
        $good['sign_str'] = $good['good_color'] . '/' . $attr_id; //规格
        $good['price'] = $good['good_price']; //单价
        $good['allprice'] = $good['good_price'] * $num + $postmanprice; //总价
        $good['postman'] = $postmanprice;
        $res = ['status'=>200,'msg'=>$good];
        return $res;
    }
    /**
     * 从购物车进去的详情
     */
    public function gouwuche($ids)
    {
        $ids = trim($ids,',');
        $have = Db::table('up_self_car')
            ->where('id','in',$ids)
            ->where('status','<>',1)
            ->find();
        if($have){
            $res = ['status'=>0,'msg'=>'有库存不足的商品，请重新选择'];
            return $res;
        }
        $field = 'id,num,c.attr_id,good_id,good_name,price,good_thumb,sign_str';
        $field .= ',good_status,stock,is_delete';
        $cars = Db::table('up_self_car')->alias('c')
            ->join('up_self_goods g','c.goods_id=g.good_id','LEFT')
            ->join('up_self_goods_attr a','c.attr_id=a.attr_id','LEFT')
            ->where('id','in',$ids)
            ->field($field)
            ->order('updated_at DESC')
            ->select();
        $postmanprice = $this->getpostmanalltype($ids,2);
        $price_data = [
            'allprice' => $postmanprice,
            'postman' => $postmanprice
        ];
        foreach ($cars as $k=>$v){
            $good_sta = $v['good_status'];
            $attr_sta_stock = $v['stock'];
            $attr_sta_del = $v['is_delete'];
            if($good_sta == 2){
                $res = ['status'=>0,'msg'=>$v['good_name'] . '已下架'];
                return $res;
            }else{
                if($attr_sta_stock < $v['num']){
                    $res = ['status'=>0,'msg'=>$v['good_name'] . $v['sign_str'] . '的库存不足'];
                    $res = ['status'=>0,'msg'=>'库存不足'];
                    return $res;
                }
                if($attr_sta_del == 1){
                    $res = ['status'=>0,'msg'=>$v['good_name'] . $v['sign_str'] . '的规格已失效'];
                    $res = ['status'=>0,'msg'=>'库存不足'];
                    return $res;
                }
            }
            $price_data['allprice'] += $v['num']*$v['price'];
            //总邮费的计算：TODO
        }
        $res = ['status'=>200,'msg'=>$cars,'price_data' => $price_data];
        return $res;
    }
    /**
     * 从购物车进去的详情（增补）
     */
    public function gouwucheps($ids,$sondata)
    {
        $ids = trim($ids,',');
        $have = Db::table('up_self_car')
            ->where('id','in',$ids)
            ->where('status','<>',1)
            ->find();
        if($have){
            $res = ['status'=>0,'msg'=>'有下架的商品，请重新选择'];
            return $res;
        }
        $field = 'id,num,good_id,good_name,good_price price,good_thumb,good_color,good_stock,car_good_year';
        $field .= ',good_status,attr_id';
        $field .= ',good_coding,good_coding_less';

        $cars = Db::table('up_self_car')->alias('c')
            ->join('up_goods g','c.goods_id=g.good_id','LEFT')
            ->where('id','in',$ids)
            ->field($field)
            ->order('updated_at DESC')
            ->select();
        $postmanprice = $this->getpostmanalltype($ids,2);
        $price_data = [
            'allprice' => $postmanprice,
            'postman' => $postmanprice
        ];
        foreach ($cars as $k=>$v){
            $sondata['uson_year'] = $v['car_good_year'];
            $insize = $this->getInSizeForGood($v['good_id'],$v['attr_id'],$sondata);
            if($insize == false){
                return ['status'=>0,'msg'=>'有不符合尺码的商品，请重新选择尺码'];
            }
            $realp = getGoodsRealPrice($v['good_coding'],$v['car_good_year'],$sondata);
            $cars[$k]['price'] = $realp;
            $v['price'] = $realp;
//            $cars[$k]['stock'] = $v["good_{$v['attr_id']}"];
            $cars[$k]['stock'] = $v["good_stock"];
            $cars[$k]['sign_str'] = $v["good_color"] . '/' . $v['attr_id'];
            $good_sta = $v['good_status'];
//            $attr_sta_stock = $v['good_'.$v['attr_id']];
            $attr_sta_del = 0;
            if($good_sta == 2){
                //商品下架，不是某个尺码下架
                $res = ['status'=>0,'msg'=>$v['good_name'] . '已下架'];
                return $res;
            }
            $price_data['allprice'] += $v['num']*$v['price'];
            //总邮费的计算：TODO
        }
        if(empty($cars)){
            $res = ['status'=>0,'msg'=>'购物车数据为空'];
            return $res;
        }
        $price_data['allprice'] = round($price_data['allprice'],2);
        $price_data['postman'] = round($price_data['postman'],2);
        $res = ['status'=>200,'msg'=>$cars,'price_data' => $price_data];
        return $res;
    }
    //获取邮费，type：1是单件，id是商品id，2是购物车，id是购物车id
    public function getpostmanalltype($ids,$type,$num='')
    {
        $postconfig = Db::table('up_postman_config')->where('id',1)->find();
        $post_man = $postconfig['default_price'];
        if($type == 1){
            $good_count = $num;
        }else{
            $cardata = Db::table('up_self_car')->alias('car')
                ->join('up_goods g','car.goods_id=g.good_id','left')
                ->field('car.num,g.good_type,g.good_pinming')
                ->where('id','in',$ids)
                ->select();
            $three = ['棉外套','棉衣','冬季外套','混纺呢大衣']; // 品名
            $good_count = 0;
            foreach ($cardata as $k => $v){
                if($v['good_type'] == '配饰'){
                    $ji = 0;
                }elseif($v['good_type'] == '秋服'){
                    $ji = 2;
                }elseif($v['good_type'] == '冬服'){
                    $ji = 2;
                    if(in_array($v['good_pinming'],$three)){
                        $ji = 3;
                    }
                }else{
                    $ji = 1;
                }
                $good_count = $good_count + ($ji*$v['num']);
            }
        }
        if($good_count > $postconfig['default_num']){
//                $bei_shu = ceil(($good_count - $postconfig['default_num'])/$postconfig['over_num']);
            //TODO：查找这些商品的类型，并换算对应的数量：
            //1、冬服,夏服,礼服,秋服,西服,配饰
            $bei_shu = $good_count - $postconfig['default_num'];
            $moremoney = $bei_shu * $postconfig['over_price'];
            $post_man += $moremoney;
        }
        return $post_man;
    }
    /**
     * 获取传给erp的编号
     */
    public function getUniqueForErp()
    {

    }
    /**
     * 支付回调处理
     */
    public function alltypespay($num,$back_order_id,$queryId='')
    {
        $today = date('Y-m-d H:i:s');
        $table_good = 'up_self_goods';
        $order = Db::table('up_self_order')->where('order_no',$num)
            ->field('order_id,is_pay,order_contract,total_price,user_id,order_id,order_cancel_status')->find();
        if($order){
            if($order['order_contract'] != 1){
                $table_good = 'up_goods';
            }
            if($order['is_pay'] != 1 && $order['order_cancel_status'] == 1){
                Db::startTrans();
                try{
                    //改订单状态
                    $update = [
                        'is_pay' => 1,
                        'order_back_order_id' => $back_order_id,
                        'order_query_id' => $queryId,
                        'pay_time' => $today,
                    ];
                    Db::table('up_self_order')->where('order_no',$num)->update($update);
                    //加商品销量
                    $field = 'goods_id,num,attr_id,erp_ak';
                    $details = Db::table('up_self_order_detail')->where('order_id',$order['order_id'])->field($field)->select();
                    foreach ($details as $k=>$v){
                        Db::table($table_good)->where('good_id',$v['goods_id'])->setInc('good_sales',$v['num']);
                    }
                    Db::commit();
                    //平台收入
                    allInRevenue(1,$order['total_price'],$order['user_id'],$order['order_contract'],$order['order_id']);
                    //支付成功通知：
                    $title = '下单成功';
                    $content = '下单成功，友情提醒：快递发出15天内未收到货物，请及时联系我司客服，核实订单情况；快递发出超过20天未收到货物，也未与我司客服联系，我司将无法处理。';
                    allInNotice($title,$content,2,$order['user_id'],$order['order_id'],$order['order_contract']);
                    try{
                        $this->Jpush(1, $order['user_id'], '下单成功', ['n_id' => $order['order_id'],'type' => $order['order_contract'],'n_type' => 2]);
                    }catch(\Exception $e){
                    }
                    return true;
                }catch (\Exception $e) {
                    Db::rollback();
                    return false;
                }
            }else{
                return false;
            }
        }else{
            $error = [
                'orderno' => $num,
                'backno' => $back_order_id,
                'time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_zz_error_order')->insert($error);
            if($res){
                return true;
            }else{
                return false;
            }
        }

    }
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        return $push->send();
    }
    /**
     * 根据user_id获取当前绑定的学生信息
     * @param $user_id
     * @return array
     */
    protected function getSonByUser($user_id)
    {
        $res = [
            'status' => 0,
            'msg' => '没有选择学生，请先选择学生'
        ];
        $sonid = Db::table('up_u_user')->where('user_id',$user_id)->value('user_son_id');
        if($sonid){
            $data = Db::table('up_u_user_son')->where('uson_id',$sonid)
                ->field('uson_id,uson_username,user_gender,uson_year,uson_school,uson_grade,uson_idcard,uson_size')
                ->find();
            if($data){
                $res = [
                    'status' => 200,
                    'msg' => $data
                ];
            }else{
                $res = [
                    'status' => 0,
                    'msg' => '学生选择失效，请重新选择学生进行购买'
                ];
            }

        }
        return $res;
    }
    protected function getStudentGoods($school_id,$year,$sex,$type='',$less_code='',$getyear=''){
        extract(input());
        $school = Db::table('up_school')
            ->where('school_id',$school_id)
            ->field('school_history,school_erp,school_status,school_no_years')
            ->find();
        //1、学校要是下架了，则看不到所有的商品
        if(empty($type)){
            $codes = array();
            if($school['school_status'] != 1){
                return $codes;
            }
        }
        //2、如果学校禁止了某些年份，则不展示这些年份的
        //3、只展示符合性别的
        $codewhere = [
            'sg_sex' => ['in',"$sex,3"],
        ];
        $codewhere2 = [
            'sg_school_erp' => $school['school_erp'],
        ];
        if($school['school_no_years']){
            $codewhere['sg_year'] = ['not in',$school['school_no_years']];
        }
        //现在的逻辑是，一定是只有这一年的，不是当年的也会只找当年的(但是购物车就比较特殊了，要看到所有之前选择的)
        if($getyear === 2){ //购物车来的
            if($school['school_history'] == 1){
                $codewhere2['sg_year'] = $year;
            }
        }else{
            $codewhere2['sg_year'] = $year;
        }

        if($type){
            //如果存在Q版，则确认下这个Q版在不在这个用户所在学校里的当年的，如果不在，返回正常，如果在，返回Q
            //肯定有值，因为列表就是从这个条件里出去的
            if($type == 2){ //商品里这个尺码是有Q版的，但是销售数据里不一定有
                $paixu = 'DESC';
                //这种情况比较特殊，如果我那一年没有Q版，下一年有了Q款，恰好后台又全放开了这所学校，则先查下当年有没有Q版，没有的话也是ASC
                $nowhave = Db::table('up_school_good')
                    ->where($codewhere)
                    ->where($codewhere2)
//                        ->where('sg_year',$year)
                    ->where('sg_good_coding_less',$less_code)
                    ->where('sg_status',1)
                    ->where("sg_good_q",2)
                    ->find();
                if(empty($nowhave)){
                    $paixu = 'ASC';
                }
            }else{ //商品里这个尺码是没有Q版的，但是有可能这个款号有Q版，所有正序排一定给的是正常的
                $paixu = 'ASC';
            }

            $codes = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->where('sg_good_coding_less',$less_code)
                ->where('sg_status',1)
                ->order("sg_good_q $paixu")
                ->find();
        }else{
            $codewhere['sg_good_q'] = 1;
            $codewhere['sg_status'] = 1;
            $codes = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->column('sg_good_coding');
            //这个unset放开就可以展示多年份了
            //unset($codewhere2['sg_year']);
            $years = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->group('sg_year')
                ->column('sg_year');
            if($getyear === 1){
                return ['codes' => $codes , 'years' => $years];
            }
        }
        return $codes;
    }
    protected function getStudentGoodsByForeach($school_id,$year,$sex,$cars){
        extract(input());
        $res = array();
        foreach ($cars as $k=>$v) {
            $year = $v['car_good_year'];
            //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            $less_code = Db::table('up_good_spec')
                ->where('spec_good_coding_less', $v['good_coding_less'])
                ->where('spec_size', $v['attr_id'])
                ->where('spec_size_q', 2)
                ->value('spec_good_coding_less');
            if ($less_code) { //说明此款号有Q款，再去判断
                $type = 2;
            } else {
                $type = 1;//压根没有Q款
            }
            $less_code = $v['good_coding_less'];
            $school = Db::table('up_school')
                ->where('school_id',$school_id)
                ->field('school_history,school_erp,school_status,school_no_years')
                ->find();
            //2、如果学校禁止了某些年份，则不展示这些年份的
            //3、只展示符合性别的
            $codewhere = [
                'sg_sex' => ['in',"$sex,3"],
            ];
            $codewhere2 = [
                'sg_school_erp' => $school['school_erp'],
            ];
            if($school['school_no_years']){
                $codewhere['sg_year'] = ['not in',$school['school_no_years']];
            }
            $codewhere2['sg_year'] = $year;
//            if($school['school_history'] == 1){
//                $codewhere2['sg_year'] = $year;
//            }
            //如果存在Q版，则确认下这个Q版在不在这个用户所在学校里的当年的，如果不在，返回正常，如果在，返回Q
            //肯定有值，因为列表就是从这个条件里出去的
            if($type == 2){ //商品里这个尺码是有Q版的，但是销售数据里不一定有
                $paixu = 'DESC';
                //这种情况比较特殊，如果我那一年没有Q版，下一年有了Q款，恰好后台又全放开了这所学校，则先查下当年有没有Q版，没有的话也是ASC
                $nowhave = Db::table('up_school_good')
                    ->where($codewhere)
                    ->where($codewhere2)
//                        ->where('sg_year',$year)
                    ->where('sg_good_coding_less',$less_code)
                    ->where("sg_status",1)
                    ->where("sg_good_q",2)
                    ->find();
                if(empty($nowhave)){
                    $paixu = 'ASC';
                }
            }else{ //商品里这个尺码是没有Q版的，但是有可能这个款号有Q版，所有正序排一定给的是正常的
                $paixu = 'ASC';
            }
            $codes = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->where('sg_good_coding_less',$less_code)
                ->where('sg_status',1)
                ->order("sg_good_q $paixu")
                ->find();
            //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            $res[] = $codes;
        }

        return $res;
    }
    /**
     * 查看套装下的衣服们
     * @param oc_id
     * @return bool
     */
    public function getTaoGoods($oc_id)
    {
        extract(input());
        $field = 'goods_id,detail_id,order_id,num,unit_price,goods_info';
        $field .= ',good_name,good_thumb';
        $data = Db::table('up_self_order_detail')->alias('sd')
            ->join('up_goods g','sd.goods_id=g.good_id','LEFT')
            ->where('oc_id_erp',$oc_id)
            ->field($field)
            ->select();
        return $data;
    }
    //------------------------mww53-------------------------------------------------------

    public function askFapiao($head,$shui,$phone,$email,$mingxi,$order_no,$message)
    {
        import('org.DESDZFP', EXTEND_PATH);
        $body_json2 = array(
            'buyername' => $head,
            'taxnum' => $shui,
            'phone' => $phone,
            'address' => '',
            'account' => '',
            'payee' => '',
            'checker' => '',
            'message' => '手机号：' . $phone . '  订单号：' . $order_no . "\n" . $message,
            'orderno' => time(). rand(100000,999999),
            'invoicedate' => date('Y-m-d H:i:s'),
            'clerk' => '潘汝滨',//开票人
            'saleaccount' => '中国银行南京市南钢支行    523571906927',
            'saletaxnum' => '91320116759496005P',
            'salephone' => '025-58398860',
            'saleaddress' => '南京市沿江工业开发区浦六北路193号 ',
            'kptype' => '1',
            'tsfs' => 2,
            'email' => $email,
            'detail' => $mingxi
        );
        $body_json = array(
            'identity' => '35D31288192AFCA85722962CC6FF9BAD42C99E76F72CC964',
            'order' => $body_json2
        );
        $body = json_encode($body_json);
        $des = new \DESDZFP;
        $body = $des->encrypt($body);
        $body_json = array(
            'order' => $body
        );
        $url = 'https://nnfp.jss.com.cn/shop/buyer/allow/cxfKp/cxfServerKpOrderSync.action';
        $res = $this->curl_post($url,$body_json);
//        dump($res);die;
        if($res['status'] == '0000'){
            return ['status' => 200,'msg' => $res['fpqqlsh']];
        }else{
            return ['status' => 100,'msg' => '开票失败'];
        }
    }
    public function getFapiaoRes($fpqqlsh)
    {
        import('org.DESDZFP', EXTEND_PATH);
        $body_json = array(
            'identity' => '35D31288192AFCA85722962CC6FF9BAD42C99E76F72CC964',
            'fpqqlsh' => $fpqqlsh
        );
        $body = json_encode($body_json);
        $des = new \DESDZFP;
        $body = $des->encrypt($body);
        $body_json = array(
            'order' => $body
        );
        $url = 'http://nnfp.jss.com.cn/shop/buyer/allow/ecOd/queryElectricKp.action';
        $res = $this->curl_post($url,$body_json);
        if($res['result'] == 'success' && $res['list'][0]['c_status'] == 2){
            //TODO:改用户地址(开完票会自动发送到邮箱，所以可以不用管)
            $pdf = $res['list'][0]['c_url'];
            $img = $res['list'][0]['c_jpg_url'];
            return ['status' => 200,'msg' => '开票成功'];
        }else{
            return ['status' => 100,'msg' => '开票失败'];
        }
    }
    public function curl_post($url , $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    //-------------------------------------------erp---------------------------------------------

    /**
     * 获取erp的基础数据
     * @return mixed
     */
    public function getErpData($table,$field,$idcard=''){ //第三个参数只针对统购订单有效
        header('Access-Control-Allow-Origin:*');
        $column = 'ISACTIVE';
        $condition = 'Y';
        if($idcard){
            $column = 'IDCARD';
            $condition = $idcard;
        }
        $time = date('Y-m-d H:i:s') . '.000';
        $sip_appkey = 'app@panson.com';
        $body_json = [
            [
                'id'=>112,
                'command'=>'Query',
//                'command'=>'ObjectModify',
                'params'=>[
                    'columns' => $field,
//                    'columns' => ["AD_CLIENT_ID"],
                    'params' => [
                        'expr1' => ['condition' => '0','column' => 'SYSFLAG'],
//                        'expr1' => ['condition' => $condition,'column' => $column],
                        'expr2' => ['condition' => $condition,'column' => $column],
                        'combine' => 'and'
                    ],
                    'table' => $table,
                    'range' => '200',
//                    "partial_update" => "true",
//                    "AK" => "JSA004A",
//                    "SYSFLAG" => "1"
                ]
            ]
        ];
        $body = json_encode($body_json);
//        dump($body);die;
        $body = 'transactions=' . urlencode($body);
        $body .= '&sip_appkey=' . urlencode($sip_appkey) . '&sip_timestamp=' . urlencode($time) . '&sip_sign=' . urlencode(md5($sip_appkey . $time . md5('123')));
        $url = 'http://36.152.23.203:4916/servlets/binserv/Rest';
        $res = $this->curl_erp($url,$body);
        return $res;
    }
    /**
     * 修改erp的基础数据
     * @return mixed
     */
    public function updateErpData($table,$erp_ak,$pay='',$size=''){
        header('Access-Control-Allow-Origin:*');
        $time = date('Y-m-d H:i:s') . '.000';
        $sip_appkey = 'app@panson.com';
        $params = [
            'table' => $table,
            "partial_update" => "true",
            "AK" => $erp_ak,
            "SYSFLAG" => "1"
        ];
        if($pay){
            $params['IS_PAY'] = 1;
        }
        if($size){
            $params['VALUE2_CODE'] = $size;
        }
        $body_json = [
            [
                'id'=>112,
                'command'=>'ObjectModify',
                'params'=>$params
            ]
        ];
        $body = json_encode($body_json);
        $body = 'transactions=' . urlencode($body);
        $body .= '&sip_appkey=' . urlencode($sip_appkey) . '&sip_timestamp=' . urlencode($time) . '&sip_sign=' . urlencode(md5($sip_appkey . $time . md5('123')));
        $url = 'http://36.152.23.203:4916/servlets/binserv/Rest';
        $res = $this->curl_erp($url,$body);
        return $res;
    }
    /**
     * 发起增补订单或者售后换货通知erp
     * @return mixed
     */
    public function orderAddErpData($master,$details,$sonid,$sontable){
        header('Access-Control-Allow-Origin:*');
        $time = date('Y-m-d H:i:s') . '.000';
        $sip_appkey = 'app@panson.com';
        $body_json = [
            [
                'id'=>112,
                'command'=>'ProcessOrder',
                'params'=>[
                    'masterobj' => $master
                    , 'detailobjs' => [
                        'reftables' => [$sonid],
                        'refobjs' => [
                            [
                                'addList' => $details,
                                'table' => $sontable
                            ]
                        ],
                    ]
                ]
            ]
        ];
        $body = json_encode($body_json);
        $body = 'transactions=' . urlencode($body);
        $body .= '&sip_appkey=' . urlencode($sip_appkey) . '&sip_timestamp=' . urlencode($time) . '&sip_sign=' . urlencode(md5($sip_appkey . $time . md5('123')));
        $url = 'http://36.152.23.203:4916/servlets/binserv/Rest';
        $res = $this->curl_erp($url,$body);
        return $res;
    }
    public function curl_erp($url,$body)
    {
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
//    protected function getInSizeForGood($good_id,$attr_id)
//    {
//        $sizes = Db::table('up_good_spec')
//            ->where('spec_good_id',$good_id)
//            ->where('spec_size_type',1)
//            ->group('spec_size')
//            ->column('spec_size');
//        if(in_array($attr_id,$sizes)){
//            return true;
//        }else{
//            return false;
//        }
//    }
    protected function getInSizeForGood($good_id,$attr_id='',$sondata='')
    {
//        $codings = 'QGMBR2T280200,KDTBS6D010000,KLTBS2D010110,QGMBR2T170100,KDTBS6Y040000,QQMBS6Y040000,KLTBS2Y040100,KLTBS2Y040000,KDTBS9Y040000,KDTBS6D010100,KZTBS6D010100,KQMCS6D010000,QQMBS6D010000,KLTBS2D010300,QGMBR1T020000,KZNBS6D010000,QGMBR2T130000,KLTBS5D010200,QGMBR2T120000,KLTBS5D010000,QGMBR2T150000,KCTBS6D010200,QGMBR2T160000,KLTBS2D010000,KZTBS6Y040000,KZTBS6D010000,QGMBR1T230100,KZMBS6D010000,KCTBS6Y040000,QGMBR2T040000,KZTBS4D010100,KQMCS4D010000,KLTBS5Y040000,QQMBS2Y040500,QGMBR1T010100,KQMCS9Y040000,KDTBS4Y040100,QQMBS4Y040000,KZTBS6D010400,KDTBS6Y040510,KQMCS6Y040000,KZMBS6Y040000,QQMBM3G070200,QGMBR2T300200,KLTBSAY040000,KLTBS4D0105X0,QQMBS4D010600,QGMBR2T080000,QGMBR1T060100,QQMBS6Y040300,QGMBR2T280000,KDTBS6B050000,KLTBSAY020000,KLTBS4D010300,QGMBR2T030200,KLMBS2D010000,KLMBS2Y040000,KDTBS9Y040010,KQMCS9Y040001,KLTBSAY0401Y0';
//        $codings = explode(',',$codings);
//        $codings2 = 'QGMAR2T280200,KDTDS6D010000,KLTAS2D010100,QGMDR2T170000,KDTDS6Y040000,QQMDS6Y040000,KLTCS2Y040100,KLTAS2Y040000,KDTAS9Y040000,KDTAS6D010000,KZTAS6D010001,KQMAS6D010000,QQMDS4D010000,KLTCS2D010200,QGMDR1T020000,KZNAS6D010000,QGMCR2T130000,KLTAS5D011100,QGMDR2T120000,KLTAS5D010000,QGMCR2T150000,KCTAS6D010900,QGMCR2T160000,KLTAS2D010000,KZTAS6Y040000,KZTAS6D010000,QGMDR1T230000,KZMAS6D010000,KCTAS6Y040000,QGMDR2T040000,KZTAS4D010100,KQMAS4D010000,KLTAS5Y040000,Q111111111111,QGMDR1T010100,KQMAS9Y040000,KDTDS4Y040100,QQMDS4Y040000,KZTAS6D010310,KDTAS6Y040000,KQMAS6Y040000,KZMAS6Y040000,QQMBM3G070200,Q222222222222,KLTASAY040000,KLTAS4D0107X0,QQMDS4D010400,QGMCR2T080000,QGMDR1T060000,Q333333333333,Q444444444444,KDTAS6B050100,KLTASAY020000,KLTCS4D010000,QGMDR2T030500,KLMCS2D010000,KLMCS2Y040000,KDTAS9Y040040,KQMAS9Y040010,KLTCSAY0401Y0';
//        $codings2 = explode(',',$codings2);
        //-------判断几个特殊的学校 start --------
        $good = Db::table('up_goods')
            ->where('good_id',$good_id)
            ->field('good_coding,good_pinming,good_sex')
            ->find();
        $where = [
            'spec_good_id' => $good_id,
            'spec_size_type' => 1
        ];
        $school = Db::table('up_school')
            ->where('school_id',$sondata['uson_school'])
            ->field('school_erp,school_type')
            ->find();
        $scherp = $school['school_erp'];
        $normal = Db::table('up_school_year_code')
            ->where('school',$scherp)
            ->where('year',$sondata['uson_year'])
            ->where('code',$good['good_coding'])
            ->find();
        $normal_q = Db::table('up_school_year_code')
            ->where('school',$scherp)
            ->where('year',$sondata['uson_year'])
            ->where('codeq',$good['good_coding'])
            ->find();
        if($normal){
            if($normal['codeq']){
                $where['spec_size'] = ['<=',140];
            }
        }
        if($normal_q){
            if($normal_q['code']){
                $where['spec_size'] = ['>=',150];
            }
        }
//        if(in_array($good['good_coding'],$codings)){
//            $fqkey = array_search($good['good_coding'],$codings);
//            $fqcode = $codings2[$fqkey];
//            $scherp = Db::table('up_school')
//                ->where('school_id',$sondata['uson_school'])
//                ->value('school_erp');
//            $one = Db::table('up_school_good')
//                ->where('sg_school_erp',$scherp)
//                ->where('sg_good_coding',$good['good_coding'])
//                ->where('sg_year',$sondata['uson_year'])
//                ->where('sg_sex','in',"{$sondata['user_gender']},3")
//                ->find();
//            $two = Db::table('up_school_good')
//                ->where('sg_school_erp',$scherp)
//                ->where('sg_good_coding',$fqcode)
//                ->where('sg_year',$sondata['uson_year'])
//                ->where('sg_sex','in',"{$sondata['user_gender']},3")
//                ->find();
//            if($one && $two){
//                $where['spec_size'] = ['<=',140];
//            }
//        }
//        if(in_array($good['good_coding'],$codings2)){
//            $qkey = array_search($good['good_coding'],$codings2);
//            $qcode = $codings[$qkey];
//            $scherp = Db::table('up_school')
//                ->where('school_id',$sondata['uson_school'])
//                ->value('school_erp');
//            $one = Db::table('up_school_good')
//                ->where('sg_school_erp',$scherp)
//                ->where('sg_good_coding',$good['good_coding'])
//                ->where('sg_year',$sondata['uson_year'])
//                ->where('sg_sex','in',"{$sondata['user_gender']},3")
//                ->find();
//            $two = Db::table('up_school_good')
//                ->where('sg_school_erp',$scherp)
//                ->where('sg_good_coding',$qcode)
//                ->where('sg_year',$sondata['uson_year'])
//                ->where('sg_sex','in',"{$sondata['user_gender']},3")
//                ->find();
//            if($one && $two){
//                $where['spec_size'] = ['>=',150];
//            }
//        }
        //-------判断几个特殊的学校  end ---------
        $sizes = Db::table('up_good_spec')
            ->where($where)
            ->group('spec_size')
            ->column('spec_size');
        if($good['good_pinming'] == '领带'){
            if($school['school_type'] == 1 && in_array(100,$sizes)){
                $sizes = [100];
            }
            if($school['school_type'] == 2 && in_array(150,$sizes)){
                $sizes = [150];
            }
            if($school['school_type'] == 3 && in_array(200,$sizes)){
                $sizes = [200];
            }
        }else if($good['good_pinming'] == '领花'){
            if(in_array(000,$sizes)){
                $sizes = ['000'];
            }
        }else{
            $newSize = [];
            if($good['good_sex'] == 1 || $good['good_sex'] == 3) $newSize = [100,110,120,130,140,150,160,165,170,175,180,185,190,200];
            if($good['good_sex'] == 2) $newSize = [100,110,120,130,140,150,160,165,170,175,180,190];
            if($newSize) $sizes = array_intersect($sizes,$newSize);
        }
        if($attr_id){
            if(in_array($attr_id,$sizes)){
                return true;
            }else{
                return false;
            }
        }else{
            return $sizes;
        }

    }
    public function aaa()
    {
//        $cars = Db::table('up_goods')
//            ->where('good_coding','like','QQ%')
//            ->field('good_id,good_name,good_coding')
//            ->select();
//        dump($cars);die;
//        if($cars){
//            foreach ($cars as $k=>$v){
//                $q = substr($v['good_coding'],0,1);
//                if($q != ''){
//                    Db::table('up_goods')
//                        ->where('good_id',$v['good_id'])
//                        ->setField('good_q',1);
//                    //规格表和记录表
//                    Db::table('up_good_spec')
//                        ->where('spec_good_coding',$v['good_coding'])
//                        ->setField('spec_size_q',1);
//                    Db::table('up_school_good')
//                        ->where('sg_good_coding',$v['good_coding'])
//                        ->setField('sg_good_q',1);
//                    Db::table('up_school_good_copy')
//                        ->where('sg_good_coding',$v['good_coding'])
//                        ->setField('sg_good_q',1);
//                }
//            }
//        }
//        $data = $this->getErpData('YZ_SALE_STU',['APP_DOCNO','SYSFLAG','RESULTS']);
//        $nos = [];
//        foreach ($data[0]['rows'] as $k => $v){
//            $nos[] = $v[0];
//        }
//        $nos = '15922170265098270,15922282957614074,15922659841725349,15923869646771218,15925814213994168,15926089359743215,15926131094503450,15927153174677662,15927408502859719,202006200938411685796,202006260757426506683,202006281200045745164,202006281211093928568,202006282001181353071,202006282118185157588,202006282139598260444,202006282142097601164,202006301821386058590,202007041247033266052,app1592399658627701,app1592400067811015,15921948264512032,15921999137262977,15922027767351656,15922041459377829,15922099559612112,15922163181604911,15921942267243289,15922034193126586,15922099563435008,15922151439212348,15922693318720540,15922699715923312,15922704188635180,15922707342922973,15922709335927090,15922711671751015,15922714905043269,15922714947015786,15922718295079521,15922719078993986,15922719644657112,15922720991064940,15922220737804200,15922240207727259,15922678783992352,15922698027680868,15922000082013510,15922025949591227,15922034115128103,15922035495686222,15922099063402562,15922162988053880,15922164378653830,15922013112131474,15922034694160133,15922131901292817,15922665803368324,15922669588965354,15922678173882474,15922686377149200,15922719596700100,15922720366475081,15922720579436766,15922234831756104,15922237255718766,15922680932339459,15922703682997512,15922712823900631,15921426998893413,15921956636175901,15921996457084087';

//        $db2 = Db::connect('mysql://panson:panson2020app@121.196.57.236:3306/panson#utf8');
//        $data = $db2->table('up_zzz')
//            ->where('type','<>','')
//            ->select();
//        $nos2 = [];
//        foreach ($data as $k => $v){
//            if($v['type'] == '幼儿园'){
//                $type = 1;
//            }elseif ($v['type'] == '小学'){
//                $type = 2;
//            }else{
//                $type = 3;
//            }
//            $db2->table('up_school')->where('school_erp',$v['erp'])->setField('school_type',$type);
//        }
//        $cellname = [
//            'app订单号', '状态', '原因'
//        ];
//        $res = exportExcel('orderinfo',time(),$cellname,$nos2);
//        echo 1;die;
//        $data = $this->is_idcard('412702198901153111');
//        if($data){
//            echo 1;
//        }else{
//            echo 0;
//        }
//        dump($data);
    }
    public function is_idcard( $id )
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
        else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return FALSE;
            }
            else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ( $i = 0; $i < 17; $i++ )
                {
                    $b = (int) $id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id,17, 1))
                {
                    return FALSE;
                }
                else
                {
                    return TRUE;
                }
            }
        }

    }
    /**
     * 获取erp的基础数据
     * @return mixed
     */
    public function getErpDataForOrder($table,$type,$orderno,$param1){ //第三个参数只针对统购订单有效
        header('Access-Control-Allow-Origin:*');
        $time = date('Y-m-d H:i:s') . '.000';
        $sip_appkey = 'app@panson.com';
        $body_json = [
            [
                'id'=>112,
                'command'=>'Query',
//                'command'=>'ObjectModify',
                'params'=>[
                    'columns' => ['APP_DOCNO'],
                    'params' => [
                        'expr1' => ['condition' => $type,'column' => $param1],
                        'expr2' => ['condition' => $orderno,'column' => 'APP_DOCNO'],
                        'combine' => 'and'
                    ],
                    'table' => $table,
//                    "partial_update" => "true",
//                    "AK" => "JSA004A",
//                    "SYSFLAG" => "1"
                ]
            ]
        ];
        $body = json_encode($body_json);
        $body = 'transactions=' . urlencode($body);
        $body .= '&sip_appkey=' . urlencode($sip_appkey) . '&sip_timestamp=' . urlencode($time) . '&sip_sign=' . urlencode(md5($sip_appkey . $time . md5('123')));
        $url = 'http://36.152.23.203:4916/servlets/binserv/Rest';
        $res = $this->curl_erp($url,$body);
        return $res;
    }
    public function oss()
    {
        require_once ('../extend/aliyunoss/autoload.php');
        $dir = $_SERVER['DOCUMENT_ROOT'];
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $accessKeyId = "LTAInLhgidum0cUc";
        $accessKeySecret = "xUpOO3b4cbFzFCUJ6W7kuvKn2BLK8z";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 设置存储空间名称。
        $bucket= "lopal-dv-upload-images";
// 设置文件名称。
        $object = "test_mww2.png";
// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        $filePath = "$dir/one.png";
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $a = $ossClient->uploadFile($bucket, $object, $filePath);
            dump($a);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }

    }
    //-----------------------------
    public function tuisouthoud()
    {
//        $db2 = Db::connect('mysql://panson:panson2020app@121.196.57.236:3306/panson#utf8');
//        set_time_limit(0);//2252
//        $nophones = $db2->table('up_school_good_copy')
//            ->where('user_update_time','>=','2020-06-19 20:00:00')
//            ->where('sg_school_erp','JSA003A00')
//            ->group('sg_school_erp','JSA003A00')
//            ->select();
//        dump($nophones);die;
//        $res = Db::table('up_z_old_user_note')
//            ->where('u_phone','in',$nophones)
//            ->setField('status',2);
//        dump($res);die;
//        $uids = Db::table('up_z_old_user_note')
//            ->where('status',1)
//            ->order('u_id asc')
//            ->page(1,1000)
//            ->column('u_id');
//        $phones = Db::table('up_z_old_user_note')
//            ->where('status',1)
//            ->order('u_id asc')
//            ->page(1,1000)
//            ->column('u_phone');
//        if($phones){
//            $phones = implode($phones,',');
//            $res = $this->tuiolduser($phones);
//            if($res[0] == 'result=0'){
//                $res = Db::table('up_z_old_user_note')
//                    ->where('u_id','in',$uids)
//                    ->setField('status',2);
//                if($res){
//                    sleep(5);
//                    $uids = Db::table('up_z_old_user_note')
//                        ->where('status',1)
//                        ->order('u_id asc')
//                        ->page(1,1000)
//                        ->column('u_id');
//                    $phones = Db::table('up_z_old_user_note')
//                        ->where('status',1)
//                        ->order('u_id asc')
//                        ->page(1,1000)
//                        ->column('u_phone');
//                    $phones = implode($phones,',');
//                    $res = $this->tuiolduser($phones);
//                    if($res[0] == 'result=0') {
//                        Db::table('up_z_old_user_note')
//                            ->where('u_id', 'in', $uids)
//                            ->setField('status', 2);
//                    }
//                }
//            }
//        }

    }
    protected function tuiolduser($phone){
        return ['not time'];
//        $SpCode = '230149';
//        $LoginName = 'js_px';
//        $Password = 'panson58398860';
        $MessageContent = iconv("UTF-8", "gbk//TRANSLIT", "亲爱的家长您好！派逊校服通APP（V2.0）6月20日8点升级上线，请务必点击链接：http://suo.im/5xWOxW。下载安装。6月21日，原APP平台下线。如有疑问，请致电4000070097，给您造成的不便，敬请谅解。");
        $body = "SpCode=$SpCode&LoginName=$LoginName&Password=$Password&MessageContent=$MessageContent&UserNumber=$phone&SerialNumber=&ScheduleTime=&f=1";
        $header = array(
            'Accept:application/x-www-form-urlencoded',
            'Content-Type: application/x-www-form-urlencoded; charset=gbk'
        );
        $url = 'https://api.ums86.com:9600/sms/Api/Send.do';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = mb_convert_encoding($result,'UTF-8','GBk');
        $res = explode('&',$result);
        return $res;
    }
    public function daochudenglu()
    {
        //------------------------保留---------------------------
//        $special = ['KDTBS6Y040000','QQMBS6Y040000'];
//        $where['spec_size'] = ['<=',140];
//        if(in_array($good['good_coding'],$special) && $sondata['uson_school'] == 93 && $sondata['uson_year'] == 2019){
//            unset($where['spec_size']);
//        }
//        if($good['good_coding'] == 'QQMBS6B050400' && $sondata['uson_school'] == 430){
//            unset($where['spec_size']);
//        }
        //---------------------------------------------------
        $iods = 'KWTBL1D070000,TATBM2W010100,YLTDFEB0104Y0,YLTDFEB0104Y1,TFTEWFG090600,KWTEK7G070200,WBTBK8B190000,WBTBK8R020000,ZBTCA1D011300,QGMDR1T010000,ZBTCA1W011000,ZBTHA1G070000,MWTAD1R043100,KTTCP2G070010,XFNAJEB070000,WBTAK8G090100,ZBTHA1G091200,QGMAR2T280200,KYTAF9D010100,YLTDF9R040100,WMTBK7G070311,MWTDD1L010400,MFMDA8D011100,MFTDA8D010800,MRTBQ2D0100Y0,TAMDW1R020100,KWTAL1G090006,XFMAJ7D010020,XFNAJ7D010200,KWTEL1G070100,MWTAD1R195400,KTTCP2D010000,TPMDW1G031510,TFTFWFG092002,WLTBK8G090302,MWTBDFD010400,CDMAC4C180000,CDNAC4C180000,KWTAK8G090003,MRTAQ2R180110,KTTBFED020000,CDMCC2C160103,MFTDN2L020500,TPTAW1G030490,MWTAD1L052520,KCTBS6D010103,TPTEM1W0100Y2,WLTBK8G090103,MWTADFD012101,MWTADFD012104,TYTEA3W0100Y8,TYTEA3W0100Y9,TYTEA3W0100YA,WMTAK7G0901X8,WMTAK7G0901XH,WMTAK7G0901XQ,MLTBP6F251000,MFMDN2L020800,MFTBN2L021000,XFMAJ4D080601,XFNAJ4D080201,MWTADFD011102,WBTBK7G091301,MRTAQ2R180100,KWTAKCD080000,WLTAKCG090000,ZBTHA1G090601,WBTBK5L021010,WBTBK7G090311,MWTAD1L052801,TPMDW7G0922Y1,TPTDW7G0915Y1,ZBTGA1L020800,KLTBS5Y040000,KWTAL1R0400Y2,WLTAL1B0100Y4,PANAA5Z380000,QQMBS2Y040500,KTTAFFY040000,CCNAC3Y040000,MWTDD1G090201,WLTAK8G0904X0,MFTBN2D010510,ZBTGA1G070401,XFNAJ2D050300,MWTDD1B190100,TFTFW7G091101,XFMAJ7D010102,KWTBK8G090002,WMTBK7G070100,MLTAP5F030310,MWTAD1B070520,TPTDW1G030430,MLTAP5F010000,TPMAW1G090505,WLTBK7G070102,MFTDP5F0404X1,TFTDW1G030610,TFMFW1G0302Y0,MWTADFD011104,KLTAS6D010300,KZTBSCD010000,MWTADKB016700,KWTBL1D070200,WLTBL1R160000,KTTCPDD010000,KCTFL5D010200,TFMFX2G071401,TFTFX2G070801,KYTAF4D010301,YLTCF4D010610,KCTDX5G100500,TPMDW1B100600,TPTAW1B100200,WBTBK8G091300,MWTAD1D014100,TPTDW1L030800,CDMAC4C261600,CDNAC4C260400,MWTAD1L050501,ZBMGA1D010100,TPMFW1Y030100,TPTDW1Y030500,WMTCK8G090000,TPMFW1G030300,PBMAA6Z330300,QQMCJDY040000,MWTAD3D030500';
        $size = '70,80,90,100,110,120,130,140';
        $iods = explode(',',$iods);
        $db2 = Db::connect('mysql://panson:panson2020app@121.196.57.236:3306/panson#utf8');
        $cellname = [
            '付款日期', '订单编号', '学校ID', '学校名字', '入学年份',
            '年级','班级', '姓名', '性别', '款号',
            '品名', '尺码', '数量', '单价', '总额',
            '收件人', '收件电话', '收件地址','快递费', '订单状态', '付款流水'
        ];
        $status = ['user_gender','is_send'];
        $values = [
            'user_gender' => [1 => '男',2 => '女']
            ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
        ];
//        $res = exportExcel('orderinfo',time(),$cellname,$data,$status,$values);
        dump($iods);die;
        $two = $db2->table('up_school')
            ->where('school_name','like','%射阳%')
            ->select();
        $two = $db2->table('up_school_good')
            ->where('sg_school_erp','JSJ007A00')
            ->select();
    }
    public function delExcel()
    {
        $date = date("Ymd",(time() - 3600 * 24 * 15));
        $dirname = ROOT_PATH . 'public' . DS . 'excel/' . $date;
        $result = false;
        if (!is_dir($dirname)) {
            return 1;
        }
        $handle = opendir($dirname); //打开目录
        while (($file = readdir($handle)) !== false) {
            if ($file != '.' && $file != '..') {
                //排除"."和"."
                $dir = $dirname .'/' . $file;
                unlink($dir);
            }
        }
        closedir($handle);
        $result = rmdir($dirname) ? true : false;
        return 1;
    }
}